﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Threading.Tasks;

namespace 服务器
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket servecocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            servecocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.230.1"),3785));
            servecocket.Listen(100);
           
           
            #region 
            //Socket client= servecocket.Accept();
            //string messenage = "success";
            //client.Send(Encoding.UTF8.GetBytes(messenage));
            //while (true)
            //{
            //    byte[] data = new byte[1024];

            //int length=client.Receive(data);
            //string mes = Encoding.UTF8.GetString(data, 0, length);
            //Console.WriteLine("receive:" + mes);
            //}
           
            //servecocket.Close();
            //client.Close();
            #endregion

            servecocket.BeginAccept(AcceptCallBack, servecocket);
            Console.ReadKey();
        }
        //static byte[] data = new byte[1024];
        public static void AcceptCallBack(IAsyncResult ar)
        {
            Socket seversocket = ar.AsyncState as Socket;
            Socket clientsocket= seversocket.EndAccept(ar);
            string s = "已连接";
            clientsocket.Send(Encoding.UTF8.GetBytes(s));
            clientsocket.BeginReceive(mes.Data,mes.Startindex,mes.remainsize,SocketFlags.None,ReceiveCallBack,clientsocket);
            seversocket.BeginAccept(AcceptCallBack, seversocket);
        }
        static message mes = new message();
        public static void ReceiveCallBack(IAsyncResult ar)
        {
            Socket clientsocket = null;
            try
            {
                 clientsocket= ar.AsyncState as Socket;
            int count= clientsocket.EndReceive(ar);
                if (count == 0)
                {
                    clientsocket.Close();
                    return;
                }
                mes.addcount(count);
                mes.getmessage();
            string message=Encoding.UTF8.GetString(mes.Data, 0, count);
            Console.WriteLine("后台" + message);
            clientsocket.BeginReceive(mes.Data, mes.Startindex, mes.remainsize, SocketFlags.None, ReceiveCallBack, clientsocket);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                if (clientsocket != null)
                {
                    clientsocket.Close();
                    return;
                }
            }
            

        }
    }
}
